#include "trans.h"

int transfile(int netfd,const char* filename)
{
    train_t train;
    train.length = strlen(filename);
    strcpy(train.data,filename);

    send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);//文件名

    int fd = open("file1",O_RDWR);
    while(1){
        bzero(&train,sizeof(train));
        ssize_t ret = read(fd,train.data,sizeof(train.data));
        train.length = ret;
        send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);//文件内容
        if(ret == 0){
            break;
        }
    }
    close(fd);

    return 0;
}

int recvn(int netfd, void *buf, int length)
{
    int total = 0;//已经recv的总字节数
    char *p = (char *)buf;//void * --> char *
    while(total < length){
        int ret = recv(netfd,p+total,length-total,0);
        if(ret == 0){
            return -1;
        }
        total += ret;
    }
    return 0;
}

int recvfile(int netfd)
{
    char filename[1024] = {0};
    int length;
    recvn(netfd,&length,sizeof(int));
    recvn(netfd,filename,length);
    int fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0666);
    char buf[1024] = {0};
    while(1){
        recvn(netfd,&length,sizeof(int));
        if(length != 1000){
            printf("length = %d\n", length);
        }
        if(length == 0){
            break;
        }
        bzero(buf,sizeof(buf));
        recvn(netfd,buf,length);
        write(fd,buf,length);
    }
    close(fd);

    return 0;
}
